/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2019 Damien P. George
 * Copyright (c) 2020 Jim Mussared
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "py/runtime.h"
#include "py/stream.h"
#include "py/mphal.h"

#include "board_init.h"
#include "machine_uart.h"

#define MP_HAL_STDIO_UART_ID  0u

void mp_hal_stdio_init(void)
{
    machine_uart_obj_t * self = (machine_uart_obj_t *)machine_uart_objs[MP_HAL_STDIO_UART_ID];
    UART_Init_Type uart_init;
    uart_init.ClockFreqHz = BOARD_DEBUG_UART_FREQ;
    uart_init.BaudRate = BOARD_DEBUG_UART_BAUDRATE;
    uart_init.WordLength = UART_WordLength_8b;
    uart_init.Parity = 0;
    uart_init.StopBits = UART_StopBits_1;
    uart_init.XferMode = UART_XferMode_RxTx;
    uart_init.HwFlowControl = UART_HwFlowControl_None;
    machine_uart_hw_init(self, &uart_init);
}

int mp_hal_stdin_rx_chr(void)
{
#if 0
    while ( 0u == (UART_STATUS_RX_DONE & UART_GetStatus(BOARD_DEBUG_UART_PORT)) )
    {}
    return UART_GetData(BOARD_DEBUG_UART_PORT);
#endif
    return machine_uart_rx_data(MP_HAL_STDIO_UART_ID);
}

void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len)
{
    while (len--)
    {
#if 0
        while ( 0u == (UART_STATUS_TX_EMPTY & UART_GetStatus(BOARD_DEBUG_UART_PORT)) )
        {}
        UART_PutData(BOARD_DEBUG_UART_PORT, *str++);
#endif
        machine_uart_tx_data(MP_HAL_STDIO_UART_ID, *str++);
    }
}


/* Systick的中断服务程序。 */
void SysTick_Handler(void)
{
    systick_ms += 1;
}

void mp_hal_delay_ms(mp_uint_t ms)
{
    ms += 1;
    uint32_t t0 = systick_ms;
    while (systick_ms - t0 < ms)
    {
        MICROPY_EVENT_POLL_HOOK
    }
}

void mp_hal_delay_us(mp_uint_t us)
{
    uint32_t ms = us / 1000 + 1;
    uint32_t t0 = systick_ms;
    while (systick_ms - t0 < ms)
    {
        __WFI();
    }
}

/* EOF. */

